package com.ruiyian.netty.DataUtils;

import com.sun.jna.platform.unix.solaris.LibKstat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class DataUtils {
    public static byte[] longToBytes(long input){
//        //分配缓冲区，单位为字节，一个long类型占8个字节，所以分配为8
//        ByteBuffer byteBuffer = ByteBuffer.allocate(Long.SIZE/Byte.SIZE);
//        //参数一为起始位置（不指定默认为0），参数二为所放的值
//        byteBuffer.putLong(0, input/1000);
//        return byteBuffer.array();
        String hexString = Long.toHexString(input);
        return strtohex(hexString);
    }
    public static byte[] longToBytes(int input){
//        //分配缓冲区，单位为字节，一个long类型占8个字节，所以分配为8
//        ByteBuffer byteBuffer = ByteBuffer.allocate(Long.SIZE/Byte.SIZE);
//        //参数一为起始位置（不指定默认为0），参数二为所放的值
//        byteBuffer.putLong(0, input/1000);
//        return byteBuffer.array();
        String hexString = Integer.toHexString(input);
        return strtohex(hexString);
    }
    // 字符串16进制转真正的16进制
    public static byte[] strtohex(String strcode) {
        int len = strcode.length();  // 获取字符串长度
        byte[] bytecode = new byte[len/2];  // 根据长度的一半生成结果字节数组
        char[] chrArray = new char[2]; // 创建中间存储字符数组
        for (int x = 0; x < len; x = x + 2) {
            chrArray[0] = strcode.charAt(x);
            chrArray[1] = strcode.charAt(x + 1);
            int a = 0;
            int b = 0;
            // 获取高四字节ascall整形值
            if (((int) chrArray[0]) > 96) {
                a = (int) chrArray[0] - 87;
            } else {
                a = (int) chrArray[0] - 48;
            }
            // 获取低四字节ascall整形值
            if (((int) chrArray[1]) > 96) {
                b = (int) chrArray[1] - 87;
            } else {
                b = (int) chrArray[1] - 48;
            }
            // 计算总的整形值，并转成byte类型（255一下整形可直接转成byte，byte：-127~+127）
            bytecode[x / 2] = (byte)(a * 16 + b);
        }
        return bytecode;
    }

    public static byte[] strtohexv2(String strcode) {
        int len = strcode.length();  // 获取字符串长度
        byte[] bytecode = new byte[len/2];  // 根据长度的一半生成结果字节数组
        char[] chrArray = strcode.toCharArray();
        int num=0;
        for (int x = 0; x < len; x++) {
            if(x%2==0){
                int a = 0;
                int b = 0;
                // 获取高四字节ascall整形值
                if (chrArray[x] < 58) {
                    a = (int) chrArray[x] - 48;
                }else if(chrArray[x]<71){
                    a = (int) chrArray[x] - 55;
                }
                else if(chrArray[x]<103){
                    a = (int) chrArray[x] - 87;
                }
                // 获取低四字节ascall整形值
                if (chrArray[x+1] <58) {
                    b = (int) chrArray[x+1] - 48;
                }else if(chrArray[x+1]<71){
                    b = (int) chrArray[x+1] - 55;
                }
                else if(chrArray[x+1]<103){
                    b = (int) chrArray[x+1] - 87;
                }
                // 计算总的整形值，并转成byte类型（255一下整形可直接转成byte，byte：-127~+127）
                bytecode[num] = (byte)(a * 16 + b);
                num++;
            }
        }
        return bytecode;
    }
    // 消防数据处理函数
    public static Map<String,String> fireboxdataprocess(String fireboxdatabytes){
        Map<String,String> fireboxdatamap = new HashMap<String,String>();
        byte[] fire_box_data_byte = DataUtils.strtohex(fireboxdatabytes);
        // 消防水带
        if(fire_box_data_byte[1]==(byte)0x01){
            fireboxdatamap.put("onefireHose", "正常");
        }
        else {
            fireboxdatamap.put("onefireHose", "脱落");
        }
        if(fire_box_data_byte[3]==(byte)0x01){
            fireboxdatamap.put("twofireHose", "正常");
        }
        else {
            fireboxdatamap.put("twofireHose", "脱落");
        }
        // 消防水枪
        if(fire_box_data_byte[5]==(byte)0x01){
            fireboxdatamap.put("onefireNozzle", "正常");
        }
        else {
            fireboxdatamap.put("onefireNozzle", "脱落");
        }
        if(fire_box_data_byte[7]==(byte)0x01){
            fireboxdatamap.put("twofireNozzle", "正常");
        }
        else {
            fireboxdatamap.put("twofireNozzle", "脱落");
        }
        // 灭火器
        if(fire_box_data_byte[9]==(byte)0x01){
            fireboxdatamap.put("onefireExtinguisher", "正常");
        }
        else {
            fireboxdatamap.put("onefireExtinguisher", "不在位");
        }
        if(fire_box_data_byte[11]==(byte)0x01){
            fireboxdatamap.put("twofireExtinguisher", "正常");
        }
        else {
            fireboxdatamap.put("twofireExtinguisher", "不在位");
        }
        // 消防窗
        if(fire_box_data_byte[13]==(byte)0x01){
            fireboxdatamap.put("fireWindow", "正常");
        }
        else {
            fireboxdatamap.put("fireWindow", "打开");
        }
        // 泡沫液位
        if(fire_box_data_byte[15]==(byte)0x01){
            fireboxdatamap.put("foamlevelstate", "缺液");
        }
        else {
            fireboxdatamap.put("foamlevelstate", "正常");
        }
        // 消防管水压
        fireboxdatamap.put("waterPressure", String.valueOf(fire_box_data_byte[17]));
        // 终端状态
        if(fire_box_data_byte[19]==(byte)0x01){
            fireboxdatamap.put("status", "正常");
        }
        else if(fire_box_data_byte[19]==(byte)0x02){
            fireboxdatamap.put("status", "有报警");
        }
        else {
            fireboxdatamap.put("status", "离线");
        }
        return fireboxdatamap;
    }

    public static String devEntoChinese(String devEn){
        switch (devEn){
            case "onefireHose":
                return "一号消防水带";
            case "twofireHose":
                return "二号消防水带";
            case "onefireNozzle":
                return "一号消防水枪";
            case "twofireNozzle":
                return "二号消防水枪";
            case "onefireExtinguisher":
                return "一号灭火器";
            case "twofireExtinguisher":
                return "二号灭火器";
            case "fireWindow":
                return "消防窗";
            case "foamlevelstate":
                return "泡沫液位";
            case "waterPressure":
                return "消防管水压";
            default:
                return "设备名称错误";
        }
    }
    public static byte[] getMsgBoardArray(String msg) throws IOException {
        // 按照英文逗号进行分割
        String[] msgList = msg.split(",");
        String msg1 = msgList[0];
        // 转成gbk编码的16进制
        byte[] gbkMsg1 = msg1.getBytes(Charset.forName("GBK"));
        String msg2 = msgList[1];
        byte[] gbkMsg2 = msg2.getBytes(Charset.forName("GBK"));
        // 将情报板协议哥各个部分进行准备 02+msgHead+msg1+msgMid+msg+crc+03
        String msgHead = "30303130706C61792E6C73742B000000005B506C61796C6973745D0D0A4974656D5F4E6F3D310D0A4974656D303D3530302C312C352C5C6673333233325C433030303030305C5330305C63323535323535303030303030";
        String msgMid = "205C6673333233325C433030303033325C5330305C63323535323535303030303030";
        // 将16进制字符串转成真正的16进制数
        byte[] charArrMsgHead = strtohexv2(msgHead);
        byte[] charArrMsgMid = strtohexv2(msgMid);
        int index = 0;
        byte[] result = new byte[charArrMsgHead.length + charArrMsgMid.length + gbkMsg1.length + gbkMsg2.length];
        for (byte c : charArrMsgHead) {
            result[index++] =  c;
        }
        for (byte c : gbkMsg1) {
            result[index++] = c;
        }
        for (byte c : charArrMsgMid) {
            result[index++] = c;
        }
        for (byte c : gbkMsg2) {
            result[index++] = c;
        }
        int crc16Value = CRCUtils.calculateCRC16XMODEM(result);
        String crcStr = String.format("%x", crc16Value);
        byte[] crcBytes = strtohexv2(crcStr);
        // 进行最后拼接
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] head = new byte[1];
        head[0] = 0x02;
        byte[] end = new byte[1];
        end[0] = 0x03;
        outputStream.write(head);
        outputStream.write(result);
        outputStream.write(crcBytes);
        outputStream.write(end);
        return outputStream.toByteArray();
    }

    // 入口管控广播指令生成
    public static byte[] getSpeakerArray(String msg) throws IOException{
        String msgAdd = "#" + msg;
        byte[] gbkSpeakerMsg = msgAdd.getBytes(Charset.forName("GBK"));
        return gbkSpeakerMsg;
    }

    // 除入口管控的其他广播指令生成
    public static byte[] getSpeakerArray(int address, String msg) throws IOException {
        int msgLen = 7 + msg.length()*2; // 9个固定长度+中文的长度
        byte[] result = new byte[msgLen];
        result[0] = (byte) address;
        result[1] = 0x10;
        result[2] = 0x00;
        result[3] = 0x01;
        result[4] = 0x00;
        result[5] = (byte) msg.length();
        result[6] = (byte) (msg.length()*2);
        // 获取中文数据
        byte[] gbkSpeakerMsg = msg.getBytes(Charset.forName("GBK"));
        int index = 7;
        for (byte c : gbkSpeakerMsg) {
            result[index++] = c;
        }
        String crc16Value = CRCUtils.getCRCModbus(result);
//        System.out.println(crc16Value);
        byte[] crcBytes = strtohexv2(crc16Value);
        // 进行最后拼接
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(result);
        outputStream.write(crcBytes);
        return outputStream.toByteArray();
    }

    public static void main(String argv[]) throws Exception {
        String a = "文明驾驶，注意安全";
        byte[] q = DataUtils.getSpeakerArray(2, a);
//        System.out.println(a.length());
//        byte[] gbkMsg1 = a.getBytes(Charset.forName("GBK"));
        for(byte i :q){
            System.out.print(String.format("%02x ", i));
        }
//        byte a = (byte) 0x05;
//        String hexString = "";
//        if(a>0){
//            hexString = String.format("%d.%d", a/10, a%10);
//        }
//        else if(a<0){
//            a = (byte) Math.abs(a);
//            hexString = String.format("-%d.%d", a/10, a%10);
//        }
//        else {
//            hexString = "0";
//        }

//        System.out.println(hexString);
//        System.out.println(devEntoChinese("onefireHose"));
//        OutboundUtils.alarmPush("黄陀尖隧道","k120+300", "消防泡沫", "缺液");
//        OutboundUtils.getJobInfo("5e961eee-accf-458c-83a4-8fae27d7d790", "e8e8d65c-e7e8-4177-b493-1371ab96fb03");
//        for(byte r:getMsgBoardArray("低温预警,谨防结冰")){
//            if(r<16&&r>=0){
//                System.out.print(String.format("0%x", r));
//            }
//            else {
//                System.out.print(String.format("%x", r));
//            }
//        }
    }
}
